package memberservice

import (
	"com.cyt.common/model/membermodel"
	"errors"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/frame/g"
)

type MemberService struct{
	MemberModel  membermodel.MemberModel
}

// 保存
func (s *MemberService) SaveMember(m interface{}) error {
	var member *membermodel.MemberModel
	if err := gconv.Struct(m, &member); err != nil {
		return err
	}

	memberInfo, _ := s.MemberModel.FindOneByCondition(g.Map{"username": member.Username})
	if memberInfo != nil {
		return errors.New("用户名已存在");
	}

	// 加密密码
	member.Password = s.MemberModel.PasswordEncrypt(member.Password)
	if _, err := s.MemberModel.Model().OmitEmpty().Save(member); err != nil {
		return err
	}
	return nil
}

// 修改
func (s *MemberService) UpdateMember(m interface{}) error {
	var member *membermodel.MemberModel
	if err := gconv.Struct(m, &member); err != nil {
		return err
	}

	memberInfo, _ := s.MemberModel.FindOneByCondition(g.Map{"id": member.Id})
	if memberInfo.Id == 0 {
		return errors.New("用户信息不存在");
	}

	info := g.Map{"nickname":  member.Nickname}
	if _, err := s.MemberModel.Model().Where("id", member.Id).Data(info).Update(); err != nil {
		return err
	}
	return nil
}

// 删除
func (s *MemberService) DeleteMember(id uint) error {
	_, err := s.MemberModel.Model().Delete(g.Map{"id": id})
	return err
}